package cn.qingyun.gis.modules.scenes.util;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.scenes.entity.RgeoResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class GdRgeoTool {

    @Value("${qingyun.gd.service-host:http://134.84.76.76}")
    public void setBaseUrl(String baseUrl) {
        GdRgeoTool.baseUrl = baseUrl;
    }

    private static String baseUrl;


    public synchronized static RgeoResult getAddressByRgeo(double poiLng, double poiLat) {

        HttpRequest httpRequest = HttpUtil.createGet(String.format("%s/rgeo/get/address?location=%s,%s", baseUrl, poiLng, poiLat));

        try {
            HttpResponse httpResponse = httpRequest.timeout(1000).execute();
            if (httpResponse.isOk()) {
                JSONObject parseObj = JSONUtil.parseObj(httpResponse.body());
                JSONObject parseObjByPath = parseObj.getByPath("data.list[0]", JSONObject.class);

                if (!parseObjByPath.isEmpty()) {
                    String address = parseObjByPath.getByPath("formatted_address", String.class);
                    String city = parseObjByPath.getByPath("addressComponent.city", String.class);
                    String district = parseObjByPath.getByPath("addressComponent.district", String.class);
                    String town = parseObjByPath.getByPath("addressComponent.township", String.class);
                    String road = parseObjByPath.getByPath("addressComponent.streetNumber.street", String.class);
                    String roadNo = parseObjByPath.getByPath("addressComponent.streetNumber.number", String.class);
                    String cityCode = parseObjByPath.getByPath("addressComponent.citycode", String.class);
                    String districtCode = parseObjByPath.getByPath("addressComponent.adcode", String.class);
                    String townCode = parseObjByPath.getByPath("addressComponent.towncode", String.class);

                    return RgeoResult.builder()
                            .cityCode(cityCode)
                            .districtCode(districtCode)
                            .townCode(townCode)
                            .city(city)
                            .district(district)
                            .town(town)
                            .road(road)
                            .roadNo(roadNo)
                            .address(address)
                            .build();
                }
            }
        } catch (Exception e) {
            log.debug("逆地理解析失败", e);
            throw new CommonException("调用地址解析接口失败！");
        }
        return null;
    }
}
